package com.trailer.base.base

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.PagerAdapter
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.QMUIViewPager
import com.qmuiteam.qmui.widget.tab.QMUITab
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator
import com.qmuiteam.qmui.widget.tab.QMUITabSegment
import com.trailer.base.R
import com.trailer.base.inter.IPagerAdapter
import com.trailer.base.utils.UiSwitch

/**
 * Mine Base Fragment
 *
 * @param <VM>
 * @param <B>
</B></VM> */
abstract class BTabFragment<VM : BViewModel<*>, B : ViewDataBinding> : BFragment<VM, B>(), IPagerAdapter {

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        initTabs()
        initPager()

    }

    protected fun tabs(): QMUITabSegment {
        return binding.root.findViewById(R.id.tabs)
    }

    protected fun viewPager(): QMUIViewPager {
        return binding.root.findViewById(R.id.view_pager)
    }


    private fun initPager() {
        val mPagerAdapter: PagerAdapter = object : FragmentPagerAdapter(childFragmentManager) {
            override fun getItem(position: Int): Fragment {
                return getPageItem(position)
            }

            override fun getCount(): Int {
                return getPageCount()
            }
        }
        viewPager().adapter = mPagerAdapter
        tabs().setupWithViewPager(viewPager(), false)
    }

    abstract fun createTabs(tabBuilder: QMUITabBuilder): Array<QMUITab>

    private fun initTabs() {
        tabs().setIndicator(QMUITabIndicator(QMUIDisplayHelper.dp2px(context(), 3), false, true))
        val builder = tabs().tabBuilder()
        builder
                .skinChangeWithTintColor(false)
                .setSelectColor(Color.parseColor("#59C2A3"))
                .setNormalColor(Color.parseColor("#999999"))
                .setTypeface(Typeface.DEFAULT_BOLD, Typeface.DEFAULT)
                .setDynamicChangeIconColor(false)

        val createdTabs = createTabs(builder)
        createdTabs.forEach {
            tabs().addTab(it)
        }

    }
    override fun <T> single(clazz: Class<T>?) {
        UiSwitch.single(context(), clazz)
    }

}
